package com.ouman.luoliluoli;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.HttpHelper;
import com.ouman.luoliluoli.utils.NetworkHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public class LoginFragment extends Fragment {


    private OnFragmentInteractionListener mListener;
    private NetworkHelper networkHelper;
    private ProgressDialog progressDialog;
    private SharedPreferences preferences;

    public LoginFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);

        //check network connection
        networkHelper = new NetworkHelper();

        Toast.makeText(getActivity(), "welcome! all checked, please login or register.", Toast.LENGTH_SHORT).show();
        final EditText editTextUserName = (EditText) view.findViewById(R.id.editTextUserName);
        final EditText editTextPassword = (EditText) view.findViewById(R.id.editTextPassword);

        Button loginButton = (Button) view.findViewById(R.id.button_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (networkHelper.isConnect(getActivity())){
                    final String username = editTextUserName.getText().toString();
                    final String passWord = editTextPassword.getText().toString();

                    if(username.equals("") || passWord.equals("")){
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("WARNING");
                        builder.setMessage("要输入用户名和密码啊..");
                        builder.setNegativeButton("取消", null);
                        builder.setPositiveButton("我知道了", null);
                        builder.show();
                    }else if(username.equals("习近平") || username.equals("金天")){
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("WARNING");
                        builder.setMessage("你这个用户名太屌了吧，低调点会死啊..");
                        builder.setNegativeButton("取消", null);
                        builder.setPositiveButton("我低调点", null);
                        builder.show();
                    }else{
                        progressDialog = new ProgressDialog(getActivity());
                        progressDialog.setCancelable(true);
                        progressDialog.setMessage("作死的登录中...");
                        progressDialog.setIndeterminate(true);
                        progressDialog.setCancelable(false);
                        progressDialog.show();

                        // 开始上天
                        new Thread(){
                            public void run(){
                                try{
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("user_email", username);
                                    jsonObject.put("user_password", passWord);
                                    System.out.println("Json: " + jsonObject.toString());

                                    final GlobalConstants globalConstants = new GlobalConstants();
                                    HttpHelper httpHelper = new HttpHelper();
                                    try{
                                        String response = httpHelper.postJsonData(GlobalConstants.API_LOGIN, jsonObject);
                                        JSONObject responseJson = new JSONObject(response);

                                        System.out.println(responseJson.toString());
                                        String status = responseJson.getString("status");

                                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                                        SharedPreferences.Editor editor = preferences.edit();

                                        if (status.equals("success")){
                                            String userId = responseJson.getJSONObject("data").getString("user_id");
                                            System.out.println("login user_id got: === " + userId);
                                            editor.putString("userId", userId);
                                            editor.apply();
                                            Message msg = Message.obtain();
                                            msg.what = 0;
                                            doPostHandler.sendMessage(msg);
                                        } else if (status.equals("fail")){
                                            Message msg = Message.obtain();
                                            msg.what = 1;
                                            doPostHandler.sendMessage(msg);

                                        } else if (status.equals("info")){
                                            Message msg = Message.obtain();
                                            msg.what = 2;
                                            doPostHandler.sendMessage(msg);
                                        } else if (status.equals("error")){
                                            Message msg = Message.obtain();
                                            msg.what = 3;
                                            doPostHandler.sendMessage(msg);
                                        }

                                    } catch (IOException e){

                                    }


                                } catch (JSONException e){
                                    System.out.print(e);
                                }
                            }
                        }.start();

                    }

                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("WARNING");
                    builder.setMessage("当前网都没有，登陆个鸡*.");
                    builder.setNegativeButton("取消", null);
                    builder.setPositiveButton("强行登陆", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent main = new Intent(getActivity(), MainActivity.class);
                            getActivity().startActivity(main);
                        }
                    });
                    builder.show();
                }

            }
        });
        Button registerButton = (Button) view.findViewById(R.id.button_register);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().getFragmentManager().beginTransaction().replace(R.id.fragment_container_login, new RegisterFragment()).commit();

            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private Handler doPostHandler = new Handler(){
        public void handleMessage(Message msg){
            //登陆成工
            if (msg.what == 0){
                // login success
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "登陆成功 欢迎回来!", Toast.LENGTH_SHORT).show();

                Intent main = new Intent(getActivity(), MainActivity.class);
                getActivity().startActivity(main);
                getActivity().finish();
                preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("isLogin", true);
                editor.apply();
            } else if (msg.what == 1){
                // user exist but invalid password
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "密码不正确, 真的不正确", Toast.LENGTH_SHORT).show();

            } else if (msg.what == 2){
                // user doest not exist should register
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "用户不存在, 请开始你的表演", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 3){
                // error about post json data or something else
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "error, 出现重大错误, 我先冷静一下你稍后再试", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
